import { defineStore } from 'pinia'
import { login as loginApi, getUserInfo as getUserInfoApi } from '@/api/user'
import { setToken, getToken, removeToken, setUserInfo, getUserInfo as getStorageUserInfo, clearStorage } from '@/utils/storage'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken() || '',
    userInfo: getStorageUserInfo() || null,
    roles: [],
    permissions: []
  }),

  getters: {
    isLogin: (state) => !!state.token,
    username: (state) => state.userInfo?.username || '',
    avatar: (state) => state.userInfo?.avatar || '',
    nickname: (state) => state.userInfo?.nickname || state.userInfo?.username || ''
  },

  actions: {
    /**
     * 登录
     */
    async login(loginForm) {
      try {
        const { username, password } = loginForm
        const res = await loginApi({ username, password })
        
        if (res.data.token) {
          this.token = res.data.token
          setToken(res.data.token)
          return true
        }
        return false
      } catch (error) {
        console.error('登录失败：', error)
        return false
      }
    },

    /**
     * 获取用户信息
     */
    async getUserInfo() {
      try {
        const res = await getUserInfoApi()
        if (res.data) {
          this.userInfo = res.data
          this.roles = res.data.roles || []
          this.permissions = res.data.permissions || []
          setUserInfo(res.data)
          return res.data
        }
        return null
      } catch (error) {
        console.error('获取用户信息失败：', error)
        return null
      }
    },

    /**
     * 退出登录
     */
    async logout() {
      try {
        // 可以调用后端登出接口
        // await logoutApi()
        
        this.token = ''
        this.userInfo = null
        this.roles = []
        this.permissions = []
        clearStorage()
        
        router.push('/login')
      } catch (error) {
        console.error('退出登录失败：', error)
      }
    },

    /**
     * 重置 Token
     */
    resetToken() {
      this.token = ''
      this.userInfo = null
      this.roles = []
      this.permissions = []
      removeToken()
    }
  }
})
